'''

Case Type： 套接字文件
Case Name： 套接字文件改名
Create At:  2020/06/29
Owner    :  n@ningyali
Descption:  1.获取套接字文件路径 2.获取套接字文件名 3.修改套接字文件名称 4.执行sql并行脚本，正常运行 5.连接数据库(预期失败) 5.还原

'''

import os
import sys
import unittest
from yat.test import Node
from yat.test import macro

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import *
from testcase.utils.Constant import Constant


class SocketRename(unittest.TestCase):
    sh = CommonSH()
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case087.py start------------')
        self.dbUserNode = Node(node='dbuser')
        self.rootNode = Node()
        self.data_path = macro.DB_INSTANCE_PATH
        self.com = Common()
        self.Constant = Constant()
        self.sqlfile1 = 'bx1.sql'
        self.sqlfile2 = 'bx2.sql'

    def test_socket_rename(self):
        self.log.info('----------------------------test:套接字文件改名-----------------------------')
        # 获取套接字文件路径
        get_socket_dir_cmd = f"show unix_socket_directory;"
        self.log.info(get_socket_dir_cmd)
        msg = self.sh.executDbSql(get_socket_dir_cmd)
        self.log.info(msg)
        msg = msg.splitlines()
        socket_dir = msg[-2].strip()
        self.log.info(socket_dir)

        # 获取套接字文件名
        get_file_list_cmd = f'ls -a {socket_dir}'
        self.log.info(get_file_list_cmd)
        file_list = self.dbUserNode.sh(get_file_list_cmd).result()
        self.log.info(file_list)
        socket_file_name = ''
        for file in file_list.split():
            self.log.info(file)
            if (self.dbUserNode.db_port not in file) or ('lock' in file):
                pass
            else:
                socket_file_name = file
        self.log.info(socket_file_name)

        socket_file_path = os.path.join(socket_dir, socket_file_name)
        new_path = os.path.join(socket_dir, 'test')
        try:
            # 修改套接字文件名称
            rename_cmd = f"mv {socket_file_path} {new_path}"
            self.log.info(rename_cmd)
            rename_msg = self.dbUserNode.sh(rename_cmd).result()
            self.log.info(rename_msg)
            self.assertEqual(rename_msg, '')

            # 目标主机新建路径
            self.to_path = os.path.dirname(self.data_path) + '/test_script/'
            # 目标主机文件路径
            self.newsql_path1 = os.path.join(self.to_path, self.sqlfile1)
            self.newsql_path2 = os.path.join(self.to_path, self.sqlfile2)
            # 拷贝文件
            self.com.scp_file(self.rootNode, self.sqlfile1, self.to_path)
            self.com.scp_file(self.rootNode, self.sqlfile2, self.to_path)

            # 执行sql并行脚本，正常执行
            sql_bx_cmd = f'''
                        source {macro.DB_ENV_PATH};    
                        gsql -h {self.dbUserNode.db_host} -d {self.dbUserNode.db_name} -p {self.dbUserNode.db_port} -U '{self.dbUserNode.db_user}' -W '{self.dbUserNode.db_password}' -f {self.newsql_path1} &
                        gsql -h {self.dbUserNode.db_host} -d {self.dbUserNode.db_name} -p {self.dbUserNode.db_port} -U '{self.dbUserNode.db_user}' -W '{self.dbUserNode.db_password}' -f {self.newsql_path2} &
                        wait
                        '''
            self.log.info(sql_bx_cmd)
            sql_bx_msg = self.dbUserNode.sh(sql_bx_cmd).result()
            self.log.info(sql_bx_msg)
            self.assertNotIn('ERROR', sql_bx_msg)

            # 通过socket连接数据库（预期失败）
            socket_conn_cmd = f'source {macro.DB_ENV_PATH};'
            socket_conn_cmd += f'gsql -d {self.dbUserNode.db_name} -p {self.dbUserNode.db_port} -h {socket_dir} -l'
            self.log.info(socket_conn_cmd)
            conn_msg = self.dbUserNode.sh(socket_conn_cmd).result()
            self.log.info(conn_msg)
            self.assertNotIn(self.Constant.CONN_DB_SUCCESS_MSG, conn_msg)
        finally:
            # 还原socket文件名
            mod_cmd = f"mv {new_path} {socket_file_path}"
            self.log.info(mod_cmd)
            chmod_msg = self.dbUserNode.sh(mod_cmd).result()
            self.log.info(chmod_msg)
            self.assertEqual(chmod_msg, '')

            # 删除scp的脚本
            self.com.scp_file(self.rootNode, self.sqlfile1, self.to_path, True)
            self.com.scp_file(self.rootNode, self.sqlfile2, self.to_path, True)

    def tearDown(self):
        self.log.info('--------------Opengauss_Reliability_Dbsys_Case087:用例执行完毕-----------------')
